package service;


import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static util.DBUtil.conn;

// 电影服务类
public class MovieService {

    public static void addMovie(String id, String name, String director, int duration, String genre, String description) {
        try(PreparedStatement psm=conn.prepareStatement("SELECT * FROM movies WHERE movie_id=?");){
            psm.setString(1, id);
            ResultSet rs=psm.executeQuery();
            if(rs.next()) {
                System.out.println("添加失败，ID为" + id + "的电影已存在");
                return;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try(PreparedStatement ps=conn.prepareStatement("INSERT INTO movies (director, genre,movie_id,duration,title, description) VALUES (?, ?, ?, ?, ?, ?)");){
            ps.setString(1, director);
            ps.setString(2, genre);
            ps.setString(3, id);
            ps.setInt(4, duration);
            ps.setString(5, name);
            ps.setString(6, description);
            ps.executeUpdate();
            LogService.logAction("系统", "添加电影: " + name);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void updateMovie(String id, String name, String director, int duration, String genre, String description) {
        try {
            PreparedStatement ptmt=conn.prepareStatement("UPDATE movies SET director=?, genre=?, duration=?, title=?, description=? WHERE movie_id=?");
            ptmt.setString(1, director);
            ptmt.setString(2, genre);
            ptmt.setInt(3, duration);
            ptmt.setString(4, name);
            ptmt.setString(5, description);
            ptmt.setString(6, id);
            ptmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean deleteMovie(String id) {
        try(PreparedStatement ptmt=conn.prepareStatement("DELETE FROM movies WHERE movie_id=?");){
            ptmt.setString(1, id);
            if(ptmt.executeUpdate()>0) {
                LogService.logAction("系统", "删除电影: " + id);
                return true;
            }
            else{
                System.out.println("删除失败，未找到ID为" + id + "的电影");
                return false;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getMovieById(String id) {
        try {
            PreparedStatement ptmt=conn.prepareStatement("SELECT title FROM movies WHERE movie_id=?");
            ptmt.setString(1, id);
            ResultSet rs=ptmt.executeQuery();
            if(rs.next()) {
                return rs.getString("title");
            }
            else{
                return null;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

